<?php

// 直接アクセスを拒否する
if (!defined("IN_APP"))
	exit("直接アクセスはできません。");

// ログインしたユーザーのみがアクセスできる
if (!isset($_SESSION['twitter_username']))
	exit("ログインしないとアクセスできません。");

if (@$_POST["action"] == "attendance_update")  {
	include_once("attendance_check.php");

	class Member {
		var $name, $twitter_name, $status, $id;
	}
	
	$attendance = attendanceCheck(time());
	
	$attendance_check = attendanceCheck(time());

	$hide_status = false;
	
	// 出欠チェックの結果の確認
	if ($attendance_check == 0) {
		exit();
	} else if ($attendance_check == -1) {
		$error = "ツイッターのリストからツイートを取得できませんでした。";
		showErrorPage();
	}

	$groups = array();

	$connect = connectToDb();

	// データベースからメンバーの一覧を読み込む
	$query = "SELECT users.name,users.twitter_username,users.user_id FROM group_members AS member ";
	$query .= "INNER JOIN users ON member.user_id = users.user_id ";
	$query .= "WHERE group_id = " . mysql_real_escape_string($_SESSION['group']) . " ";
	$query .= "AND (member.del_flag <> 'd' OR member.del_flag IS NULL) ";
	$query .= "ORDER BY member.sort_order ASC";

	$result = mysql_query($query, $connect);

	$attendance = array();

	if ( !$result ) {
		exit("Invalid query: $query - " . mysql_error());
	}
	else {
		while ($row = mysql_fetch_assoc($result)) {
			// そのメンバーの出欠ステータスを取得する
			$query = "SELECT status FROM attendance ";
			$query.= "WHERE group_id = " . mysql_real_escape_string($_SESSION['group']) . " ";
			$query.= "AND user_id = " . mysql_real_escape_string($row['user_id']) . " ";
			$query.= "AND date = '" . date("Y-m-d") . "' ";
			$query.= "AND (del_flag <> 'd' OR del_flag IS NULL) ";
			$query.= "ORDER BY time DESC ";
			$query.= "LIMIT 0,1";
							
			$res = mysql_query($query, $connect);
			
			$attend_row = mysql_fetch_assoc($res);
			
			if (!empty($attend_row)) {
				if ($attend_row['status'] == 1) {
					$status = "出席";
				}
				else if ($attend_row['status'] == 0) {
					$status = "欠席";
				}
			}
			else {
				$status = "未回答";
			}
			
			$member = new Member();
			$member->name = $row['name'];
			$member->id = $row['user_id'];
			$member->twitter_name = $row['twitter_username'];
			$member->status = $status;

			array_push($attendance, $member);
		}
	}
	
	$output = "";
	foreach ($attendance as $member) {
		$output.= $member->id . "|" . $member->status . "\n";
	}
	
	echo $output;
}
	
	
?>